package ua.in.hut;

import java.io.*;
import java.sql.*;
import java.util.logging.*;
import javax.servlet.*;
import javax.servlet.http.*;
import ua.org.ass.*;

/**
 *
 * @author Frick_ua
 */
public class SrvAutorization implements Servlet {

	@Override
	public void init(ServletConfig config) throws ServletException {
		try {
			db = DB.connect("localhost", 5432, "Hut", "supervisor", "admin");
		} catch (SQLException ex) {
			Logger.getLogger(SrvAutorization.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	@Override
	public ServletConfig getServletConfig() {
		return null;
	}

	@Override
	public void service(ServletRequest req, ServletResponse res)
			  throws ServletException, IOException {
		if (db == null) {
			init(null);
		}

		HttpServletResponse resp = (HttpServletResponse) res;
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		resp.addHeader("Access-Control-Allow-Origin", "*");
		String uHash = req.getParameter("uHash");
		if (uHash != null) {
			try {
				String sessionID = Authenticator.login(uHash, req.getRemoteAddr(),
						  ((HttpServletRequest) req).getHeader("User-Agent"));
				if (sessionID !=null) {
						Cookie cookie = new Cookie("sessionID", sessionID);
						cookie.setPath("\\");
						resp.addCookie(cookie);
//						HLoginPanel.createUserPanel(uHash).readHTML(resp.getWriter());
				} else {
					Log.s("Не знайдено користувача за хеш-кодом.");
					resp.getWriter().append("Користувача не знайдено.");
					resp.setStatus(401);
				}
			} catch (SQLException ex) {
				Log.s("Не можливо авторизувати.", ex);
				resp.getWriter().append("Не можливо авторизувати.");
				resp.setStatus(401);
			} catch (AuthException ex) {
				if (ex.isAlreadyAuthenticate()) {
//					resp.getWriter().append(HLoginPanel.createUserPanel(uHash).toString());
				} else {
					resp.getWriter().append(ex.getMessage());
					resp.setStatus(401);
				}
			}
		}
	}

	@Override
	public String getServletInfo() {
		return null;
	}

	@Override
	public void destroy() {
		if (db != null) {
			try {
				db.closeConnection();
			} catch (SQLException ex) {
				Logger.getLogger(SrvAutorization.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	/**
	 * Об’єкт бази данних.
	 */
	private transient DB db;
}
